<?php

namespace App\Http\Controllers\Admin\Wechat\Manager\Material;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use App\Models\Wechat\Image as WechatImage;
use App\Models\Wechat\ImageGroup;
use App\Models\Attachment;
use Validator;
use DB;
class ImageController extends AdminController
{
    /**
	 * 获取图片列表
	 * @return [type] [description]
	 */
	public function getLists(Request $request){
		$where  = [] ;
		if($request->input('wechat_image_group_id')>-1){
			$where['wechat_image_group_id'] = $request->input('wechat_image_group_id');
		}
		$size = $request->input('size');
		$page   = $request->input('page') ? $request->input('page') : 1;
		$start  = ($page-1)*$size;
		$total = WechatImage::where($where)->count();
		$list['total'] = $total;
		if($total>0){
			$wechatImages = WechatImage::where($where)->orderBy('created_at','desc')->skip($start)->take($size)->get();
            $list['list'] = $wechatImages;
		}
		$this->ajaxJson(0,'',$list);
	}

	/**
     * 上传图片
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function uploadPic(Request $request){
        $attachment = new Attachment();
        $attachment = $attachment->uploadPic($request);
        $wechatimage = new WechatImage();
        $wechatImageGroupId = (int)$request->input('wechat_image_group_id');
        if(!$wechatImageGroupId || $wechatImageGroupId<0){
        	$wechatImageGroupId = 0;
        }else{
        	$imageGroup = ImageGroup::find($wechatImageGroupId);
        	if(!$imageGroup){
        		$this->ajaxJson(1,'图片分组不存在,请刷新页面重试');
        	}
        }

        //不是剪切图的处理才会上传到微信图片库
        if(!$attachment->isBase64){
            $wechatimage->attachment_id = $attachment->id;
            $wechatimage->wechat_image_group_id = $wechatImageGroupId;
            $wechatimage->url = $attachment->url.$attachment->fileName;
            $wechatimage->name = $attachment->fileName;
            $wechatimage->save();
            if($wechatImageGroupId){
                $imageGroup->increment('total');
            }

        }
        $url = $attachment->url.$attachment->fileName;
        $this->ajaxJson(0,'上传成功',['url'=>$url]);
    }

    /**
     * 更新微信图片
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function updateInfo(Request $request){
        $id = $request->input('id');
        $wechatimage = $this->_get_one($id);
        $wechatimage->name = $request->input('name');
        $wechatimage->save();
        $this->ajaxJson(0,'更新成功');
    }

    /**
     * 图片移动分组
     * @return [type] [description]
     */
    function moveImage(Request $request){
        $wechat_image_ids = $request->input('wechat_image_ids');
        $wechat_image_group_id = $request->input('wechat_image_group_id');
        try {
            DB::beginTransaction();
            $wechatImage = DB::table('wechat_image')->where('id',$wechat_image_ids[0])->first();

            DB::table('wechat_image')->whereIn('id',$wechat_image_ids)->update(['wechat_image_group_id'=>$wechat_image_group_id]);
            DB::table('wechat_image_group')->where('id',$wechat_image_group_id)->increment('total',count($wechat_image_ids));
            DB::table('wechat_image_group')->where('id',$wechatImage->wechat_image_group_id)->decrement('total',count($wechat_image_ids));
            DB::commit();
            $this->ajaxJson(0,'移动成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'移动失败');
        }
    }

    /**
     * 获取图片
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function getOne($id){
        $wechatimage = WechatImage::find($id);
        if(!$wechatimage){
            $this->ajaxJson(1,'未知数据');
        }
        $this->ajaxJson(0,'',$wechatimage);
    }

    /**
     * 表单验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
            'wechat_image_ids' => '微信图片',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'array' => ':attribute格式错误,必须是数组',
        );

        return Validator::make($data, [
            'wechat_image_ids' => 'bail|required|array',
        ],$message,$attribute);
    }

    /**
     * 删除
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    function deleteImage(Request $request){
        $data = $request->all();
        $validator = $this->formValidator($data);
        if($validator->fails()){
            $this->ajaxJson(1,$validator->errors()->first());
        }
        $wechat_image_ids = $data['wechat_image_ids'];
        try {
            DB::beginTransaction();
            foreach ($wechat_image_ids as $wechat_image_id) {
                $wechatimage = DB::table('wechat_image')->find($wechat_image_id);
                if(!$wechatimage){
                    $this->ajaxJson(1,'未知图片数据');
                }
                DB::table('wechat_image')->where('id',$wechat_image_id)->delete();
                if($wechatimage->wechat_image_group_id){
                    DB::table('wechat_image_group')->where('id',$wechatimage->wechat_image_group_id)->decrement('total');    
                }
            }
            DB::commit();
            $this->ajaxJson(0,'删除成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'删除失败');
        }
    }

    private function _get_one($id){
        $wechatimage = WechatImage::find($id);
        if(!$wechatimage){
            $this->ajaxJson(1,'数据不存在');
        }
        return $wechatimage;
    }
}
